#include <stdio.h>
#include <sys/shm.h>
#include <signal.h>
#include <sys/ipc.h>
#include <unistd.h>
struct mybuf
{
    int pid;
    char buf[124];
}
void myfunc(int no)
{
    return ;
}
int main(void)
{

    // 适用于有血缘关系
    // int shmid = shmget(IPC_PRIVATE, 128, 0777);
    int key = ftok("a.c", 'a');
    int shmid = shmget(key, 128, IPC_CREAT | 0777);
    if (shmid < 0)
    {
        printf("create share memory faile\n");;
        return -1;
    }
    printf("create success id = %d\n", shmid);
        char *p = (char *)shmat(shmid, NULL, 0); // 设为 0 表示读写权限jk
        if (p == NULL)
        {
            perror("shmat function fail");
            exit(1);
        }
        while(1)
        {
            signal(SIGUSR2, myfunc);
            printf("parent start write\n");
            fgets(p, 128, stdin);
            // 写完，发信号给子进程，通知子进程读数据
            kill(pid, SIGUSR1);
            pause(); // 等待子进程读
        }
    else if(pid == 0)
    {
        char *r = (char *)shmat(shmid, NULL, 0); // 设为 0 表示读写权限jk
        if (r == NULL)
        {
            perror("shmat function fail");
            exit(1);
        }
        while(1)
        {
            signal(SIGUSR1, myfunc);
        pause(); // 等待父进程写
            printf("share memory data:%s\n", r);
            kill(getppid(), SIGUSR2);
        }

    }

    char *p = (char *)shmat(shmid, NULL, 0); // 设为 0 表示读写权限jk
    if (p == NULL)
    {
        perror("shmat function fail");
        exit(1);
    }

    // write share memory
    fgets(p, 128, stdin);

    // start read share memory
    printf("share memory data:%s\n", p);
    printf("share memory data:%s\n", p);


    int ret = shmdt(p);
    if (ret == -1)
    {
        perror("unmap error");
        exit(1);
    }

    // printf("share memory data:%s\n", p);

    int res = shmctl(shmid, IPC_RMID, NULL);

    return 0;
}